package cn.com.shopec.erp.product.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excel.ExcelBaseExport;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.JsonHelper;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.product.entity.ProductStock;
import cn.com.shopec.erp.product.entity.ProductStockExt;
import cn.com.shopec.erp.product.service.IProductService;
import cn.com.shopec.erp.product.service.IProductStockService;
import cn.com.shopec.erp.product.service.impl.ProductStockExcelImport;
import cn.com.shopec.erp.product.vo.ProductHistoryVo;
import cn.com.shopec.erp.product.vo.ProductStockVo;
import cn.com.shopec.erp.stock.excel.impl.ProductStockExcelExport;
import cn.com.shopec.erp.system.common.UserUtils;
import cn.com.shopec.erp.system.service.IUserService;
import cn.com.shopec.erp.system.vo.RoleVo;

@Controller
@RequestMapping("/product/productmgt")
public class ProductController {

	private static final Log log = LogFactory.getLog(ProductController.class);

	@Resource
	private IProductService productService;
	@Resource
	private IProductStockService productStockService;
	@Resource
	private IUserService userService;

	@RequestMapping("toSetVipOccupyQuantity")
	public String toSetVipOccupyQuantity(ProductStock productStock, ModelMap map) {
		try {
			productStock = productStockService.getProductStock(productStock);
			map.put("productStock", productStock);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "product/product_stock_set_vip_quentity";
	}
	

	@RequestMapping("setVipOccupyQuantity")
	@ResponseBody
	public String setVipOccupyQuantity(ProductStock productStock, ModelMap map) {
		try {
			return productStockService.setVipOccupyQuantity(productStock);
		} catch (Exception e) {
			log.error("fileUpload" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 
	 * @Title: listProductHistory
	 * @Description: 查询某一货品的历史库存记录
	 * @param productHistoryVo
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws @author:
	 *             duhui
	 * @date: 2013-5-23下午02:17:21
	 */
	@RequestMapping("/list_product_history")
	public String listProductHistory(ProductHistoryVo productHistoryVo, PageQuery pageQuery, ModelMap map) {
		try {
			PageFinder<ProductHistoryVo> pagedProdHistoryList = this.productService
					.getPagedProdHistory(productHistoryVo, pageQuery);

			String pagedProdHistoryListJson = JsonHelper2.toJson(pagedProdHistoryList.getData());
			map.put("pagedProdHistoryListJson", pagedProdHistoryListJson);

			map.put("productHistoryCount", pagedProdHistoryList.getData().size());

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/product/product_history_list";
	}

	@RequestMapping("toProductStock")
	public String toProductStock(ModelMap map) {
		try {
			List<RoleVo> roleVos = userService.getOwnRoleVos(UserUtils.getUserVo());
			map.put("roleVos", roleVos);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "product/product_stock";
	}

	@RequestMapping("productStockPageList")
	@ResponseBody
	public String productStockPageList(ProductStockVo productStockVo, PageQuery pageQuery) {
		PageFinder<ProductStockExt> page = productStockService.productStockPaged(productStockVo, pageQuery);
		ModelMap map = new ModelMap();
		map.put("Rows", page.getData());
		map.put("Total", page.getRowCount());
		return JsonHelper2.toJson(map);
	}

	@RequestMapping("exportProductStockList")
	public void exportProductStockList(ProductStockVo productStockVo, HttpServletResponse response) {
		PageFinder<ProductStockExt> page = productStockService.productStockPaged(productStockVo, null);
		ExcelBaseExport excelBaseExport = new ProductStockExcelExport(page.getData(),
				"商品库存信息_" + System.currentTimeMillis(), response);
		try {
			excelBaseExport.wirteExcel();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("downloadTemplet")
	public void downloadTemplet(HttpServletResponse response) {
		try {
			String configPath = MultiChannelConfig.class.getClassLoader().getResource("/").getPath();
			configPath = java.net.URLDecoder.decode(configPath, "utf-8");
			InputStream inStream = new FileInputStream(configPath + "stockExcelTemplet.xlsx");// 文件的存放路径
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("库存盘点模板文件.xlsx", "UTF-8"));
			byte[] b = new byte[100];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("importStock")
	@ResponseBody
	public String importStock(@RequestParam MultipartFile file, HttpServletRequest request) {
		if (!file.isEmpty()) {
			try {
				request.getSession().removeAttribute("checkProductStockList");
				ProductStockExcelImport loadExcel = new ProductStockExcelImport(file.getInputStream(),
						file.getOriginalFilename(), 1);
				List<Object> excelData = loadExcel.getList();
				if (!CollectionUtils.isEmpty(excelData)) {
					List<Map<String, Object>> rs = productStockService.checkProductStock(excelData);
					request.getSession().setAttribute("checkProductStockList", rs);
					return SZSCMConstant.SUCCESS;
				}
			} catch (Exception e) {
				log.error("fileUpload" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("checkProductStockPageList")
	@ResponseBody
	public String checkProductStockPageList(PageQuery pageQuery, HttpServletRequest request) {
		ModelMap map = new ModelMap();
		map.put("Rows", 0);
		map.put("Total", 0);
		if (request.getSession().getAttribute("checkProductStockList") != null) {
			List<Map<String, Object>> checkProductStockList = (List<Map<String, Object>>) request.getSession()
					.getAttribute("checkProductStockList");
			if (!checkProductStockList.isEmpty()) {
				int pageNo = pageQuery.getPage();
				int pageSize = pageQuery.getPageSize();
				int rowCount = checkProductStockList.size();
				int start = (pageNo - 1) * pageSize;
				if (rowCount % pageSize == 0) {
					map.put("Rows", checkProductStockList.subList(start, start + pageSize));
				} else {
					if (pageNo * pageSize > rowCount) {
						map.put("Rows", checkProductStockList.subList(start, rowCount));
					} else {
						map.put("Rows", checkProductStockList.subList(start, start + pageSize));
					}
				}
				map.put("Total", rowCount);
			}
		}
		return JsonHelper2.toJson(map);
	}

	@RequestMapping("toCheckProductStock")
	public String toCheckProductStock(String pTabid, ModelMap map) {
		try {
			List<RoleVo> roleVos = userService.getOwnRoleVos(UserUtils.getUserVo());
			map.put("roleVos", roleVos);
			map.put("pTabid", pTabid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "product/product_stock_check";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("synchronizationToSys")
	@ResponseBody
	public String synchronizationToSys(String ids, HttpServletRequest request) {
		if (request.getSession().getAttribute("checkProductStockList") != null) {
			List<Map<String, Object>> checkProductStockList = (List<Map<String, Object>>) request.getSession()
					.getAttribute("checkProductStockList");
			List<ProductStock> productStocks = new ArrayList<ProductStock>();
			String[] idsT = JsonHelper.fromJson(ids, String[].class);
			for (String id : idsT) {
				for (Map<String, Object> map : checkProductStockList) {
					if (id.equals(map.get("uniqueId").toString())) {
						ProductStock productStock = new ProductStock();
						productStock.setId(map.get("id").toString());
						productStock.setWhNo(map.get("whNo").toString());
						productStock.setSupNo(map.get("supNo").toString());
						productStock.setProdNo(map.get("prodNo").toString());
						productStock.setCommoNo(map.get("commoNo").toString());
						productStock.setProductTotal(Long.valueOf(map.get("productTotal").toString()));
						productStock.setQualifiedQuantity(Long.valueOf(map.get("qualifiedQuantity").toString()));
						productStock.setDefectiveQuantity(Long.valueOf(map.get("defectiveQuantity").toString()));
						productStocks.add(productStock);
					}
				}
			}
			if (!productStocks.isEmpty()) {
				String msg = productStockService.synchronizationToSys(productStocks);
				if (SZSCMConstant.SUCCESS.equals(msg)) {
					for (String id : idsT) {
						for (Map<String, Object> map : checkProductStockList) {
							if (id.equals(map.get("uniqueId").toString())) {
								map.put("isSynchronization", "1");
								map.put("sysProductTotal", map.get("productTotal"));
								map.put("sysQualifiedQuantity", map.get("qualifiedQuantity"));
								map.put("sysDefectiveQuantity", map.get("defectiveQuantity"));
							}
						}
					}
				}
				return msg;
			}
		}
		return SZSCMConstant.FAIL;
	}

}
